import React, { Suspense } from 'react'
import { BrowserRouter, Route, Routes, Navigate, useLocation } from "react-router-dom"
import routes from "./pages"
import { routerItem } from "../interface"

function index() {
    const BeforeEach = ({children}:{children:JSX.Element|any}) => {
        const location=useLocation()
        const token=localStorage.getItem('token')
        if(!token&&location.pathname!=='/login'){
            return <Navigate to={'/login'}/>
        }
        return children
    }
    const mapRouter = (route:routerItem[]) => {
        const newRouter=route.map((v,i)=>{
            return v.path?<Route key={i} 
            path={v.path} 
            element={<BeforeEach>{v.element}</BeforeEach>}>
                {
                    v.children&&mapRouter(v.children)
                }
            </Route>
            :<Route key={i} path={v.from} element={<Navigate to={v.to}></Navigate>}></Route>
        })
        return newRouter
    }
    return (
        <Suspense fallback={<h1 style={{ textAlign: "center" }}>加载中，请稍后！！！</h1>}>
            <BrowserRouter>
                <Routes>
                {mapRouter(routes)} 
                </Routes>
            </BrowserRouter>
        </Suspense>
    )
}

export default index
